const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const pool = require('./db');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const users = require('./users'); // 导入用户配置文件

/*
  ./users.js 的文件内容写法

  const users = {
    admin: { username: 'admin', password: 'admin', role: 'admin' },
    test: { username: 'test', password: '123', role: 'admin' },
    user: { username: 'user', password: 'user123', role: 'user' }
  };
  
  module.exports = users;
*/

const app = express();
app.use(bodyParser.json());
app.use(cors());

console.log('再次启动了服务')


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  }
});

const upload = multer({ storage });

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = Object.values(users).find(user => user.username === username && user.password === password);

  if (user) {
    res.json({ success: true, role: user.role });
  } else {
    res.json({ success: false });
  }
});

// 添加菜品
app.post('/dishes', upload.single('image'), async (req, res) => {
  const { name, description } = req.body;
  const image_url = req.file ? `/uploads/${req.file.filename}` : null;

  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }

  try {
    const [result] = await pool.query(
      'INSERT INTO dishes (name, description, image_url, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())',
      [name, description, image_url]
    );
    res.status(201).json({ id: result.insertId, name, description, image_url });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取所有菜品
app.get('/dishes', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM dishes');
    res.json(rows);
  } catch (error) {
    console.error('Error fetching dishes:', error);
    res.status(500).json({ error: error.message });
  }
});

// 修改菜品
app.put('/dishes/:id', upload.single('image'), async (req, res) => {

  const { id } = req.params;
  const { name, description } = req.body;
  const image_url = req.file ? `/uploads/${req.file.filename}` : req.body.image_url;

  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }

  try {
    const [rows] = await pool.query('SELECT image_url FROM dishes WHERE id = ?', [id]);
    const oldImageUrl = rows[0]?.image_url;

    const [result] = await pool.query(
      'UPDATE dishes SET name = ?, description = ?, image_url = ?, updated_at = NOW() WHERE id = ?',
      [name, description, image_url, id]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: 'Dish not found' });
    }

    if (req.file && oldImageUrl) {
      const oldImagePath = path.join(__dirname, oldImageUrl);
      fs.unlink(oldImagePath, (err) => {
        if (err) {
          console.error(`Failed to delete old image file: ${oldImagePath}`, err);
        }
      });
    }

    res.json({ id, name, description, image_url });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除菜品
app.delete('/dishes/:id', async (req, res) => {
  const { id } = req.params;

  try {
    const [rows] = await pool.query('SELECT image_url FROM dishes WHERE id = ?', [id]);
    const imageUrl = rows[0]?.image_url;

    const [result] = await pool.query('DELETE FROM dishes WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: 'Dish not found' });
    }

    if (imageUrl) {
      const imagePath = path.join(__dirname, imageUrl);
      fs.unlink(imagePath, (err) => {
        if (err) {
          console.error(`Failed to delete image file: ${imagePath}`, err);
        }
      });
    }

    res.json({ message: 'Dish deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.post('/ratings', async (req, res) => {
  const { dish_id, rating, comment } = req.body;

  if (!dish_id || !rating) {
    return res.status(400).json({ error: 'Dish ID and rating are required' });
  }

  try {
    const [result] = await pool.query(
      'INSERT INTO ratings (dish_id, rating, comment, created_at) VALUES (?, ?, ?, NOW())',
      [dish_id, rating, comment]
    );
    res.status(201).json({ id: result.insertId, dish_id, rating, comment });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
// 获取指定菜品的平均评分
app.get('/dishes/:id/average-rating', async (req, res) => {
  const { id } = req.params;

  try {
    const [rows] = await pool.query(
      `SELECT average_rating 
       FROM dish_stats_view 
       WHERE dish_id = ?`, 
      [id]
    );
    const averageRating = rows.length > 0 ? rows[0].average_rating : 5;
    res.json({ average_rating: averageRating });
  } catch (error) {
    console.error('Error fetching average rating:', error);
    res.status(500).json({ error: error.message });
  }
});
// 获取指定菜品的评分记录（支持分页）
app.get('/dishes/:id/ratings', async (req, res) => {
  const { id } = req.params; // 从 URL 参数中提取菜品 ID
  const { page = 1, per_page = 5 } = req.query; // 从查询字符串中提取分页参数
  const offset = (page - 1) * per_page;

  try {
    const [rows] = await pool.query(
      'SELECT * FROM ratings WHERE dish_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
      [id, Number(per_page), Number(offset)]
    );
    res.json(rows);
  } catch (error) {
    console.error('Error fetching ratings:', error);
    res.status(500).json({ error: error.message });
  }
});
/*
// 获取指定菜品的评分记录(全部返回)
app.get('/dishes/:id/ratings', async (req, res) => {
  const { id } = req.params;

  try {
    const [rows] = await pool.query('SELECT * FROM ratings WHERE dish_id = ?', [id]);
    res.json(rows);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
*/
// 获取某天某餐的菜单
app.get('/meal-plans', async (req, res) => {
  const { date, meal } = req.query;
  try {
    const [rows] = await pool.query(`
      SELECT mp.*, d.name, d.image_url, dsv.average_rating
      FROM meal_plans mp
      JOIN dishes d ON mp.dish_id = d.id
      LEFT JOIN dish_stats_view dsv ON d.id = dsv.dish_id
      WHERE mp.date = ? AND mp.meal = ?
    `, [date, meal]);
    res.json(rows);
  } catch (error) {
    console.error('Error getting meal plans:', error);
    res.status(500).json({ error: error.message });
  }
});

// 创建或更新某天某餐的菜单
app.post('/meal-plans', async (req, res) => {
  const { date, meal, dish_ids } = req.body;
  if (!Array.isArray(dish_ids)) {
    return res.status(400).json({ error: 'dish_ids should be an array' });
  }

  console.log(`Updating meal plans for date: ${date}, meal: ${meal}, dish_ids: ${dish_ids}`);

  const conn = await pool.getConnection();
  try {
    await conn.beginTransaction();

    // 先删除现有的记录
    const [deleteResult] = await conn.query('DELETE FROM meal_plans WHERE date = ? AND meal = ?', [date, meal]);
    console.log(`Deleted rows: ${deleteResult.affectedRows}`);

    // 插入新的记录
    for (const dish_id of dish_ids) {
      console.log(`Inserting dish_id: ${dish_id}`);
      const [insertResult] = await conn.query(`INSERT INTO meal_plans (date, meal, dish_id) VALUES (?, ?, ?)`, [date, meal, dish_id]);
      console.log(`Inserted row id: ${insertResult.insertId}`);
    }

    await conn.commit();
    res.status(201).json({ message: 'Meal plan updated successfully' });
  } catch (error) {
    await conn.rollback();
    console.error('Error updating meal plans:', error);
    res.status(500).json({ error: error.message });
  } finally {
    conn.release();
  }
});

// 删除某天某餐的菜单
app.delete('/meal-plans', async (req, res) => {
  const { date, meal, dish_id } = req.body;
  try {
    const [deleteResult] = await pool.query('DELETE FROM meal_plans WHERE date = ? AND meal = ? AND dish_id = ?', [date, meal, dish_id]);
    console.log(`Deleted rows: ${deleteResult.affectedRows}`);
    res.status(204).end();
  } catch (error) {
    console.error('Error deleting meal plans:', error);
    res.status(500).json({ error: error.message });
  }
});

// 将所有路由统一添加 /api 前缀
app.use('/api', app._router);

const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server is running on port ${PORT}`);
});